<template>
  <div class="report-details-container">
    <el-card class="report-card">
      <!-- 添加体检报告和生成日期 -->
      <div class="report-title">
        <h2 style="text-align: center;">体检报告</h2>
        <p style="text-align: center; margin-bottom: 20px;">生成日期：{{ new Date().toLocaleDateString() }}</p>
      </div>

      <el-descriptions :column="1" border class="description">
        <el-descriptions-item label="体检人">
          {{ reportInfo.patientName }}
        </el-descriptions-item>
        <el-descriptions-item label="身份证号码">
          {{ reportInfo.idCard }}
        </el-descriptions-item>
        <el-descriptions-item label="体检日期">
          {{ reportInfo.reportDate }}
        </el-descriptions-item>
        <el-descriptions-item label="套餐名称">
          {{ reportInfo.packageName }}
        </el-descriptions-item>
        <el-descriptions-item label="体检报告内容">
          {{ reportInfo.reportContent }}
        </el-descriptions-item>
        <el-descriptions-item label="医生备注">
          {{ reportInfo.notes }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 固定内容的检查明细 -->
      <el-card class="check-details-card">
        <div slot="header" class="clearfix">
          <span>检查明细</span>
        </div>
        <el-table :data="checkDetails" border style="width: 100%;">
          <el-table-column prop="category" label="类别" align="center" />
          <el-table-column prop="value" label="值" align="center" />
          <el-table-column prop="reference" label="参考范围" align="center" />
        </el-table>
      </el-card>

      <div class="button-container">
        <el-button type="primary" @click="goBack">返回</el-button>
        <el-button type="success" @click="printToPDF">打印为PDF</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import html2pdf from "html2pdf.js";
import { getReport } from "@/api/physicalExamination/report";
import { listPatient } from "@/api/hospital/patient";
import { getPackage } from "@/api/physicalExamination/package";

export default {
  name: "ReportDetails",
  data() {
    return {
      reportInfo: {
        patientName: '',
        idCard: '',
        reportDate: '',
        packageName: '',
        reportContent: '',
        notes: '',
        id: ''
      },
      checkDetails: [
        { category: '身高', value: '172cm', reference: '150-190' },
        { category: '体重', value: '71kg', reference: '50-100' },
        { category: '视力', value: '左眼1.2, 右眼1.0', reference: '0.8-1.5' },
        { category: '血压（高压）', value: '80mmHg', reference: '90-120' },
        { category: '血压（低压）', value: '115mmHg', reference: '60-90' },
        { category: '心率', value: '心脏', reference: '60-100' },
        { category: '血氧', value: '95%', reference: '95-100' },
        { category: '体温', value: '36.5℃', reference: '36-37' }
      ]
    };
  },
  watch: {
    '$route.query.id'(newId, oldId) {
      if (this.$route.path === '/physicalExamination/report/details' && newId !== oldId) {
        this.resetReportInfo();
        this.fetchReportDetails();
      }
    }
  },
  created() {
    if (this.$route.path === '/physicalExamination/report/details') {
      this.fetchReportDetails();
    }
  },
  methods: {
    async fetchReportDetails() {
      try {
        const id = this.$route.query.id;
        if (!id) {
          this.$message.error('未找到报告ID');
          return;
        }
        const { data } = await getReport(id);
        if (!data) {
          this.$message.error('报告数据不存在');
          return;
        }

        let patientInfo = { name: '未知', idCard: '未知' };
        if (data.patientId) {
          const patientRes = await listPatient({ patientIds: data.patientId });
          const patient = patientRes.rows && patientRes.rows.length > 0 ? patientRes.rows[0] : null;
          if (patient) {
            patientInfo = {
              name: patient.name || '未知',
              idCard: patient.idCard || '未知'
            };
          }
        }

        let packageName = '未知套餐';
        if (data.packageId) {
          const packageRes = await getPackage(data.packageId);
          packageName = packageRes.data?.packageName || `未知套餐${data.packageId}`;
        }

        this.reportInfo = {
          patientName: patientInfo.name,
          idCard: patientInfo.idCard,
          reportDate: data.reportDate || '未知日期',
          packageName: packageName,
          reportContent: data.reportContent || '暂无报告内容',
          notes: data.notes || '暂无备注',
          id: data.id || '未知'
        };
      } catch (error) {
        this.$message.error('获取报告详情失败');
        console.error(error);
      }
    },
    goBack() {
      this.$router.push('/physicalExamination/report');
    },
    resetReportInfo() {
      this.reportInfo = {
        patientName: '',
        idCard: '',
        reportDate: '',
        packageName: '',
        reportContent: '',
        notes: '',
        id: ''
      };
    },
    printToPDF() {
      const element = this.$el.querySelector('.report-card');
      const buttonContainer = element.querySelector('.button-container');
      if (buttonContainer) {
        buttonContainer.style.display = 'none'; // 临时隐藏按钮
      }

      const options = {
        margin: [10, 10, 10, 10], // A4 边距
        filename: `体检报告_${this.reportInfo.patientName}_${this.reportInfo.reportDate}.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: {
          scale: 2,
          useCORS: true,
          windowWidth: 595, // A4 宽度 (210mm ≈ 595px)
          removeContainer: true // 移除可能的额外容器影响
        },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
      };

      html2pdf().from(element).set(options).toPdf().get('pdf').then((pdf) => {
        const totalPages = pdf.internal.getNumberOfPages();
        for (let i = 1; i <= totalPages; i++) {
          pdf.setPage(i);
          pdf.setFontSize(10);
          pdf.text(`第 ${i} 页 / 共 ${totalPages} 页`, pdf.internal.pageSize.width / 2, pdf.internal.pageSize.height - 10, { align: 'center' });
        }
        pdf.setProperties({
          title: '体检报告',
          subject: '体检详情'
        }); // 清除可能的元数据乱码
        if (buttonContainer) {
          buttonContainer.style.display = ''; // 恢复按钮显示
        }
        pdf.save();
      }).catch((error) => {
        console.error('PDF 生成失败:', error);
      });
    }
  }
};
</script>

<style scoped>
.report-details-container {
  padding: 0;
  background-color: #fff;
  width: 595px; /* A4 宽度 (210mm ≈ 595px) */
  margin: 0 auto;
  box-sizing: border-box;
  height: 842px; /* A4 高度 (297mm ≈ 842px) */
  overflow: hidden;
}

/* 报告标题样式 */
.report-title h2 {
  font-size: 28px;
  color: #303133;
  font-weight: bold;
  margin: 10px 0;
}

.report-title p {
  font-size: 14px;
  color: #606266;
  margin: 5px 0;
}

/* 报告卡片样式 */
.report-card {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 0;
  box-shadow: none;
  padding: 10px;
  box-sizing: border-box;
}

.description {
  margin-bottom: 20px;
}

.description .el-descriptions-item__label {
  font-weight: bold;
  background-color: #f8f8f8;
  width: 120px;
}

.description .el-descriptions-item__content {
  padding: 8px;
}

/* 检查明细卡片样式 */
.check-details-card {
  border: 1px solid #dcdfe6;
  border-radius: 0;
  box-shadow: none;
  margin-bottom: 20px;
}

.check-details-card .el-table {
  font-size: 14px;
  width: 100%;
}

.check-details-card .el-table th {
  background-color: #f8f8f8;
  font-weight: bold;
}

.check-details-card .el-table td {
  word-break: break-word; /* 确保长文本换行 */
}

.button-container {
  margin-top: 20px;
  text-align: center;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

/* 网页显示样式 */
@media screen {
  .report-details-container {
    padding: 20px;
    background-color: #f5f7fa;
    width: 100%;
    height: auto;
    max-width: 595px; /* 限制最大宽度为 A4 */
  }
}

/* 打印样式 */
@media print {
  .report-card,
  .check-details-card {
    border: 1px solid #000;
    width: 100%;
    padding: 0;
    margin: 0;
    page-break-inside: avoid; /* 避免页面内断行 */
  }

  .report-title h2 {
    font-size: 24px;
  }

  .report-title p {
    font-size: 12px;
  }

  .button-container {
    display: none !important;
  }

  .report-details-container {
    padding: 0;
    width: 595px; /* A4 宽度 */
    height: 842px; /* A4 高度 */
    margin: 0;
  }

  .el-table {
    font-size: 12px;
    width: 100% !important;
    table-layout: fixed; /* 固定布局，确保列宽均匀 */
  }

  .el-table th,
  .el-table td {
    padding: 4px;
    border: 1px solid #000;
    word-break: break-all; /* 强制换行 */
  }

  .el-table th {
    background-color: #f0f0f0;
  }

  /* 强制列宽填满 A4 宽度 */
  .el-table th:nth-child(1),
  .el-table td:nth-child(1) {
    width: 33.33%; /* 类别 */
  }

  .el-table th:nth-child(2),
  .el-table td:nth-child(2) {
    width: 33.33%; /* 值 */
  }

  .el-table th:nth-child(3),
  .el-table td:nth-child(3) {
    width: 33.33%; /* 参考范围 */
  }
}
</style>
